﻿using System;
using System.Collections.Generic;
using System.Text;
using reactiveBT.Utilities;

namespace reactiveBT.BT
{
    /// <summary>
    /// 条件分支节点
    /// 仅在第一次或Reset后执行判断函数。为真则开始遍历子节点。遍历子节点过程中不关心判断函数返回值
    /// 调用父类Branch的Tick函数，当父类Tick返回非Continue时均将reset标记位置为真
    /// 测试成功
    /// </summary>
    public class ConditionalBranch : Branch
    {
        System.Func<int,bool> fn;
        bool tested = false;
        bool res = false;
        public ConditionalBranch(System.Func<int,bool> fn)
        {
            this.fn = fn;
        }
        public override BTState Tick(int BTid)
        {
            if (needToReset)
            {
                this.ResetSelf();
                base.ResetChildren();
                needToReset = false;
            }
            if (!tested)
            {
                res = fn(BTid);
            }
            if (res)
            {
                var result = base.Tick(BTid);
                switch(result)
                {
                    case BTState.Continue:
                        return BTState.Continue;
                    default:
                        needToReset = true;
                        return result;
                }
            }
            else
            {
                needToReset = true;
                return BTState.Failure;
            }
        }
        protected override void ResetSelf()
        {
            base.ResetSelf();
            tested = false;
        }
    }
}
